package com.xframe.xdal.core.model;


import com.xframe.xdal.core.model.sqlbuilder.SqlExpression;
import com.xframe.xdal.core.model.sqlbuilder.SqlKey;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;

/**
 * 功能描述:通用的数据库操作结果返回对象
 *
 * @author xufeng
 * @version 1.0
 * @date 2022-09-26
 */
@Data
@Log4j2
public class DataAccessResult<T> {
    /**
     * 开始时间
     */
    @Setter(AccessLevel.NONE)
    @Getter(AccessLevel.NONE)
    private Long startTime = 0L;
    /**
     * 结束时间
     */
    @Setter(AccessLevel.NONE)
    @Getter(AccessLevel.NONE)
    private Long endTime = 0L;
    /**
     * 构造的SQL结果集
     */
    @Setter(AccessLevel.NONE)
    private SqlExpression sqlExpression;
    /**
     * 操作后的结果
     */
    @Setter(AccessLevel.NONE)
    private T result;

    /**
     * 执行过程中的异常信息
     */
    @Setter(AccessLevel.NONE)
    private Exception exception;

    @Setter(AccessLevel.NONE)
    private int code = 0;


    /**
     * 执行过程是否成功
     */
    public Boolean getSuccessFlag(){
        return this.code == 0;
    }

    /**
     * 操作模式
     */
    @Setter(AccessLevel.NONE)
    private SqlKey sqlKey;

    /**
     * 存在异常则获取异常，无异常则返回结果
     *
     * @return T
     * @throws Exception 异常
     */
    public T getResultIfErrorOnThrow() throws Exception {
        if (this.code == 0 && this.exception == null) {
            return this.result;
        }
        throw this.exception;
    }

    /**
     * 构造函数
     */
    public DataAccessResult(SqlKey sqlKey) {
        this.startTime = System.currentTimeMillis();
        this.result = null;
        this.code = 0;
        this.sqlExpression = null;
        this.sqlKey = sqlKey;
    }



    /**
     * 设置完成
     *
     * @param result        执行结果
     * @param sqlExpression sql 表达式对象
     */
    public void setDone(T result, SqlExpression sqlExpression) {
        this.code = 0;
        this.result = result;
        this.sqlExpression = sqlExpression;
        endTime = System.currentTimeMillis();
    }
    /**
     * 设置失败错误
     *
     * @param exception     异常
     * @param sqlExpression sql表达式对象
     */
    public void setError(int errCode, Exception exception, SqlExpression sqlExpression) {
        this.code = errCode;
        this.result = null;
        this.sqlExpression = sqlExpression;
        this.exception = exception;
        endTime = System.currentTimeMillis();
    }

    /**
     * 设置失败错误
     *
     * @param exception 异常
     */
    public void setError(int errCode,Exception exception) {
        this.code = errCode;
        this.result = null;
        this.sqlExpression = null;
        this.exception = exception;
        endTime = System.currentTimeMillis();
    }

    /**
     * 获得运行的总时长(毫秒)
     */
    public Long getTotalDuration() {
        return endTime - startTime > 0 ? endTime - startTime : 0L;
    }

//    @Override
//    public String toString(){
//        return this.successFlag.toString();
//    }
}
